import optparse
import socket


def port_scan(ip, port):
    global s

    try:
        s = socket.socket()
        s.settimeout(5)  # 设置一个连接超时的时间
        if s.connect_ex((ip, port)) == 0:
            # connect_ex() 在连接失败时不会做出异常，而是返回一个错误码，如果连接成功，则返回0（即没有错误）
            print('[+]Host:{},Port{},Status:OPEN'.format(ip, port))
        else:
            print('[+]Host:{},Port{},Status:CLOSE'.format(ip, port))
    except Exception as e:
        print(e)
        pass
    finally:
        s.close()


def main():
    """命令解析、端口扫描"""
    parser = optparse.OptionParser('< Usage>')  # optparse 是一个用于解析命令行参数的库
    parser.add_option('-i', dest='ip', type='string', help='target ip')
    parser.add_option('-p', '--port', dest='port', type='string',
                      help='target port,可以用单个端口，也可以用一个端口范围，比如8080，9000')
    opts, args = parser.parse_args()
    ip = opts.ip
    port = opts.port
    if ip is None or port is None:
        print('请输入-h查看命令手册')
        return
    try:
        if '-' in port:
            start_port, end_port = port.split('-')
            for p in range(int(start_port), int(end_port) + 1):
                port_scan(ip, p)
            else:
                port_scan(ip, int(port))
    except:
        print('请输入-h查看命令手册')


if __name__ == '__main__':
    main()
